package com.gitee.zhangchenyan.takin.common.utils;

import cn.hutool.core.convert.Convert;

import java.util.ArrayList;
import java.util.List;


/**
 * @Deacription 树形工具类
 * @Author zl
 * @Date 2022/3/27 14:39
 * @Version 1.0
 **/
public class Tree<T extends BaseTree<T>> {

    public List<T> getAll(List<T> treeList) {
        List<T> firstTreeList = new ArrayList<>();
        for (T tree : treeList) {
            if (tree.getPid() == null) {
                firstTreeList.add(tree);
            }
        }
        for (T firstTree : firstTreeList) {
            getChildren(firstTree, treeList, firstTree.getId());
        }
        return firstTreeList;
    }

    public void getChildren(T superTree, List<T> treeList, long pid) {
        List<T> childrenTreeList = new ArrayList<>();
        for (T tree : treeList) {
            if (tree.getPid() != null && tree.getPid() == pid) {
                List<Long> ids;
                if (superTree.getCascadesIds() != null) {
                    ids = new ArrayList<>(superTree.getCascadesIds());
                } else {
                    ids = new ArrayList<>();
                }
                ids.add(pid);
                tree.setCascadesIds(ids);
                childrenTreeList.add(tree);
            }
        }
        if (childrenTreeList.size() > 0) {
            for (T tree : childrenTreeList) {
                getChildren(tree, treeList, tree.getId());
            }
            superTree.setChildren(childrenTreeList);
        }
    }

}
